package top.hencter.weibo.fragment;

import android.app.appsearch.SearchResult;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.w3c.dom.Text;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import top.hencter.weibo.R;
import top.hencter.weibo.activity.SearchResultActivity;
import top.hencter.weibo.adapter.*;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FindFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FindFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    ListView listView;
    GridView gridView;
    ArrayList<String> dataList;

    public FindFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FindFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FindFragment newInstance(String param1, String param2) {
        FindFragment fragment = new FindFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_find, container, false);
        listView = view.findViewById(R.id.hot_search_list); // 实例化热搜列表
        gridView = view.findViewById(R.id.find_grid_view);


        // =========================================================================================
        // 获取热搜项
        getHotSearchList();


        // =========================================================================================
        // 热搜图片获取
        getHotSearchImage();

        // =========================================================================================
        // 热搜项目点击
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // 获取被点击项的内容
                HashMap<String,String> map=(HashMap<String,String>)listView.getItemAtPosition(position);
                String keyWords=map.get("hot_search_title");
//                System.out.println(keyWords);
                Intent intent=new Intent(getContext(), SearchResultActivity.class);
                intent.putExtra("keyWords",keyWords);
                getContext().startActivity(intent);
            }
        });

        // =========================================================================================
        // 热搜项目搜索

        TextView searchKeyWords = view.findViewById(R.id.search_box);
        Button searchBtn = view.findViewById(R.id.search_btn);

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keyWords = searchKeyWords.getText() + "";
                Intent intent=new Intent(getContext(), SearchResultActivity.class);
                intent.putExtra("keyWords",keyWords);
                getContext().startActivity(intent);
            }
        });

        return view;
    }

    public  void getHotSearchList() {
        // 热搜项获取逻辑
        OkHttpClient hot_search_title_client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://129.28.159.96:7001/v1/test/getHotSearch")
                .build();
        hot_search_title_client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("Failure Info", e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                // 获取热搜数据并定义数据
                String hot_search_data = response.body().string();
                Log.i("Response Info", hot_search_data);
                Gson gson = new Gson();
                dataList = gson.fromJson(hot_search_data, new TypeToken<ArrayList<String>>() {
                }.getType());
                // System.out.println(dataList.get(1).toString());
                List<Map<String, String>> dates = new ArrayList<>();
                for (int i = 0; i < dataList.size(); i++) {
                    Map<String, String> map = new HashMap<>();
                    map.put("hot_search_ranking", String.valueOf(i + 1));
                    map.put("hot_search_title", dataList.get(i).toString());
                    dates.add(map);
                }

                // 定义adapter
                String[] from = {"hot_search_ranking", "hot_search_title"};             // 数据当中的字段
                int[] to = {R.id.hot_search_ranking, R.id.hot_search_title};            // 渲染到对应的组件上，组件id
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SimpleAdapter simpleAdapter =
                                new SimpleAdapter(getActivity(), dates, R.layout.find_list_item, from, to);
                        listView.setAdapter(simpleAdapter);
                    }
                });
            }
        });
        // =========================================================================================
        // 热搜图片获取

    }

    public  void getHotSearchImage() {
        // 热搜图片获取逻辑
        OkHttpClient hot_search_image_client = new OkHttpClient();
        Request imageRequest = new Request.Builder()
                .url("http://129.28.159.96:7001/v1/test/getHotImage")
                .build();
        hot_search_image_client.newCall(imageRequest).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("Failure Info", e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                // 获取热搜数据并定义数据
                String hot_search_image = Objects.requireNonNull(response.body()).string();
                Log.i("Response Info", hot_search_image);
                Gson gson = new Gson();
                ArrayList<String> dataList = gson.fromJson(hot_search_image, new TypeToken<ArrayList<String>>() {
                }.getType());

                // System.out.println(dataList);
                // 定义adapter
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        FindGridViewAdapter gridViewAdapter = new FindGridViewAdapter(getActivity(), R.layout.find_gridview_item,dataList);
                        gridView.setAdapter(gridViewAdapter);
                    }
                });
            }
        });
    }


}